/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import Flutter
import UIKit

@objc(AvoidAreaPlugin)
public class AvoidAreaPlugin: NSObject, FlutterPlugin, FlutterStreamHandler {
    private var eventSink: FlutterEventSink?
    private var eventChannel: FlutterEventChannel?

    private let methodChannelName = "flutter_avoid_area_method"
    private let eventChannelName = "flutter_avoid_area_event"

    public static func register(with registrar: FlutterPluginRegistrar) {
        let instance = AvoidAreaPlugin()
        instance.setupChannels(registrar: registrar)
    }

    private func setupChannels(registrar: FlutterPluginRegistrar) {
        let methodChannel = FlutterMethodChannel(
            name: methodChannelName,
            binaryMessenger: registrar.messenger()
        )

        let eventChannel = FlutterEventChannel(
            name: eventChannelName,
            binaryMessenger: registrar.messenger()
        )

        registrar.addMethodCallDelegate(self, channel: methodChannel)
        eventChannel.setStreamHandler(self)
    }

    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        switch call.method {
        case "addAvoidAreaListener":
            result(true)
            
        case "getWindowAvoidArea":
            guard let typeNumber = call.arguments as? NSNumber,
                  let type = SafeAreaType(rawValue: UInt(typeNumber.intValue)) else {
                result(FlutterError(code: "INVALID_ARGS", message: "Invalid or missing arguments", details: nil))
                return
            }
            let jsonString = AWSafeAreaMonitor.shared.getWindowAvoidArea(for: type)
            result(jsonString)
            
        case "removeAvoidAreaListener":
            AWSafeAreaMonitor.shared.removeAvoidAreaListener()
            result(true)
            
        default:
            result(FlutterMethodNotImplemented)
        }
    }


    // MARK: - Stream Handler

    public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
        if self.eventSink != nil {
            print("Already listening, skip duplicate listener.")
            return nil // 已经在监听，不重复注册
        }

        self.eventSink = events

        AWSafeAreaMonitor.shared.addAvoidAreaListener { safeAreas in
            events(safeAreas) // 使用当前的 eventSink
        }

        return nil
    }

    public func onCancel(withArguments arguments: Any?) -> FlutterError? {
        self.eventSink = nil
        AWSafeAreaMonitor.shared.removeAvoidAreaListener()
        return nil
    }
}

// MARK: - SafeAreaType Extension
extension SafeAreaType {
    public init?(rawValue: UInt) {
        switch rawValue {
        case 0: self = .statusBar
        case 1: self = .notch
        case 2: self = .gestureArea
        case 3: self = .keyboard
        case 4: self = .navigationToolbar
        default: return nil
        }
    }
}
